package com.zzyl.service.impl;

import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.CustomerUserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.CustomerUserService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Slf4j
@Service
public class CustomerUserServiceImpl implements CustomerUserService {
    @Autowired
    WeChatService weChatService;
    @Autowired
    CustomerUserMapper customerUserMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public LoginVo customerLogin(UserLoginRequestDto userLoginRequestDto) {
        //1.appid + secret + code调取第三方微信官方去获取openid
        String openid=weChatService.getOpenId(userLoginRequestDto);

        //5.根据phoneCode去微信官方查询手机号
        String phoneNum=weChatService.getPhoneNum(userLoginRequestDto);

        //2.根据openid去数据库查询用户信息
        Member member =customerUserMapper.selectByOpenId(openid);
        //3.不存在就新增用户
        if(!ObjectUtil.isNotEmpty(member)){
            Member member0 = Member.builder().openId(openid).phone(phoneNum).name("微信用户").build();
            //新增之后需要拿到id,需要在xml中将插入的主键id返回
            customerUserMapper.insert(member0);
        }else{
            //4.存在就不新增
            //6存在的判断手机号是否一致,不一致更新手机号
            Long id = member.getId();
           String phoneNumById = customerUserMapper.selectPhoneNumByid(id);
           if(!phoneNum.equals(phoneNumById)){
               customerUserMapper.updatePhoneNum(phoneNum,id);
           }
        }
        //7.获取用户id jwt 生成token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
        LoginVo loginVo = LoginVo.builder().token(token).nickName(member.getName()).build();

        return loginVo;
    }
}
